package com.yuntsg.ruiijn.databse_search.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.DeleteRequest;
import co.elastic.clients.elasticsearch.core.DeleteResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.SimpleQuery;
import com.yuntsg.nnsfcp.common.utils.RedisUtil;
import com.yuntsg.nnsfcp.common.utils.UserUtil;
import com.yuntsg.ruiijn.database.mapper.WosBasicMapper;
import com.yuntsg.ruiijn.databse_search.BaseService;
import com.yuntsg.ruiijn.databse_search.entity.*;
import com.yuntsg.ruiijn.databse_search.mapper.FileDetailsMapper;
import com.yuntsg.ruiijn.paperana.utils.esutils.EsServerEntity;
import common.bean.RRException;
import common.bean.ReturnImage;
import common.util.*;
import common.vo.*;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Rect;
import org.opencv.imgcodecs.Imgcodecs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.awt.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
@DS("master")
@SuppressWarnings("all")

public class FileDetailService extends BaseService<FileDetailsMapper, FileDetails> {
    @Autowired
    private ElasticsearchClient restClient;
    @Autowired
    private ExtractUtil extractUtil;
    @Autowired
    private MinioUtil minioUtil;
    @Autowired
    private NacosUtil nacosUtil;
    @Autowired
    private SearchSelfService searchSelfService;
    @Autowired
    private SearchRecordService searchRecordService;
    @Autowired
    private BussService bussService;
    @Autowired
    private ImageComparison imageComparison;
    @Autowired

    private WosBasicMapper wosBasicMapper;

    @Autowired
//    private final RedisUtil redisUtil;
    private RedisUtil redisUtil;

    @Autowired
    private CutImageUtil cutImageUtil;
    @Autowired
    private FeatureService featureService;
    @Value("${upload.path}")
    public String uploadPath;
    @Value("${upload.tempPath}")
    public String tempPath;
    @Value("${central.search.singleNum}")
    private Integer singleNum;
    @Value("${central.search.allNum}")
    private Integer allNum;

    @Resource
    UserUtil userUtil;

    public void editText(Integer id, String content) throws Exception {
        PriVectorTextRes textDoc = new PriVectorTextRes(content, userUtil.getUid(), id);
        this.saveOrUpdate(this.getById(id).setTxtContent(content));
        restClient.index(updateReq -> updateReq.index("text_vector_self").document(textDoc));
    }

    public void deleteText(Integer id) throws IOException {
        DeleteRequest deleteRequest = DeleteRequest.of(s -> s.index("text_vector_self").id(String.valueOf(id)));
        restClient.delete(deleteRequest);
        this.removeById(id);
    }

    public void deleteImg(Integer id) throws IOException {
        DeleteRequest deleteRequest = DeleteRequest.of(s -> s.index("image_vector_self").id(String.valueOf(id)));
        DeleteResponse delete = restClient.delete(deleteRequest);
        this.removeById(id);
    }

    // 2023年10月5日15:06:59 进行匹配es相似片段
    @SneakyThrows
    public boolean matchEsRes(String str, Double simi) {
        if (simi == null) {
            simi = 0.3;
        }
        boolean isMath = false;
        List<EsServerEntity> hits = searchSelfService.pubParticiplesRetrieval(str, 0, 1);
        if (hits.size() > 0) {
            EsServerEntity hit = hits.get(0);
            double str1 = StfUtil.genManualScore(str, HtmlUtil.cleanHtmlTag(hit.getHighlight().get("str").get(0)));
            if (str1 >= simi) {
                isMath = true;
            }
        }
        return isMath;

    }

    // 2023年10月5日15:06:59 进行匹配es相似片段
    @SneakyThrows
    public boolean matchEsResManal(String str, Integer fid, Integer uid, Double simi) {
        boolean isMath = false;
        List<Hit<JSONObject>> hits = searchSelfService.manParticiplesRetrieval(str, 0, 1, fid, uid);
        if (hits.size() > 0) {
            Hit<JSONObject> hit = hits.get(0);
            double str1 = StfUtil.genManualScore(str, HtmlUtil.cleanHtmlTag(hit.highlight().get("str").get(0)));
            if (str1 >= simi) {
                isMath = true;
            }
        }
        return isMath;

    }


    // @CacheEvict(value = "imageFeature", key = "#fid")
    public void addImg(Integer fid, MultipartFile file) {
        String upload = null;
        try {
            upload = minioUtil.upload(file.getInputStream(), userUtil.getUid(), DateUtil.today(), file.getOriginalFilename(), Scenario.pdf);
            FileDetails fileDetails = new FileDetails().setTpye(2).setFId(fid).setPath(upload);
            this.saveOrUpdate(fileDetails);
            PriVectorImgRes ImgDoc = new PriVectorImgRes(featureService.imageFeature(upload), userUtil.getUid(), fileDetails.getId());
            restClient.index(i -> i.index("image_vector_self").document(ImgDoc));
        } catch (Exception e) {
            throw new RRException("图片添加失败");
        }
    }

    // @Cacheable(cacheNames = "imageFeature", key = "#fid")
    public Map<Integer, float[]> imageFeatureWithId(Integer fid) {
        Map<Integer, float[]> result = new HashMap<>();
        Map<Integer, String> map = SimpleQuery.map(Wrappers.<FileDetailsSelf>lambdaQuery().eq(FileDetailsSelf::getFId, fid).eq(FileDetailsSelf::getTpye, 2), FileDetailsSelf::getId, FileDetailsSelf::getPath);
        for (Integer integer : map.keySet()) {
            List<Float> floats = featureService.imageFeature(map.get(integer));
            result.put(integer, ArrayUtils.toPrimitive(floats.toArray(new Float[0]), 0.0F));
        }
        return result;
    }

    //    @Cacheable(cacheNames = "imageFeatureWithIdForPub", key = "#fid")
    public Map<Integer, float[]> imageFeatureWithIdForPub(Integer fid) {
        Map<Integer, float[]> result = new HashMap<>();
        List<Integer> ids = SimpleQuery.list(Wrappers.<FileDetails>lambdaQuery().eq(FileDetails::getFId, fid).in(FileDetails::getTpye, 2, 3), FileDetails::getId);
        Map<Integer, String> map = SimpleQuery.map(Wrappers.<FileDetails>lambdaQuery().in(FileDetails::getFId, ids).in(FileDetails::getTpye, 4, 5, 6).eq(FileDetails::getCollectionStatus, 1), FileDetails::getId, FileDetails::getPath);
        for (Integer integer : map.keySet()) {
            List<Float> floats = featureService.imageFeature(map.get(integer));
            result.put(integer, ArrayUtils.toPrimitive(floats.toArray(new Float[0]), 0.0F));
        }
        return result;
    }

    public Map<Integer, float[]> imageFeatureWithIdForcontentsComparison(List<FileDetails> list) {
        Map<Integer, float[]> result = new HashMap<>();
        Map<Integer, String> map = list.stream().collect(Collectors.toMap(FileDetails::getId, FileDetails::getPath));
        for (Integer integer : map.keySet()) {
            List<Float> floats = featureService.imageFeature(map.get(integer));
            result.put(integer, ArrayUtils.toPrimitive(floats.toArray(new Float[0]), 0.0F));
        }
        return result;
    }

    /**
     * 异步获取json结果
     */

    // @Async
//    public void fetchJsonResultSigle(FileRecord fileRecord, Integer uid, Integer baseId) throws IOException {
//        Integer rid = fileRecord.getId();
//        String filePath = fileRecord.getFilePath();
//
//        List<FileDetails> listOrgin = this.list(Wrappers.<FileDetails>lambdaQuery().eq(FileDetails::getRid, rid).eq(FileDetails::getTpye, 4));
//        WosBasic wosBasic = wosBasicMapper.selectById(baseId);
//        if (listOrgin.size() > 0) {
//            List<FileDetails> list = listOrgin.stream().map(f -> {
//                f.setArray(nacosUtil.numIdentify(f.getPath()));
//                f.setVector(featureService.imageFeature(f.getPath()));
//                f.setFPath(this.getById(f.getFId()).getPath());
//                f.setPmid(filePath);
//                f.setIsWhite(imageComparison.checkWhiteBlock(f.getPath()));
//                return f;
//            }).collect(Collectors.toList());
//
//            List<ContentsComparisonRes> comparison = imageComparison.comparisonSortWithLine(list, list, uid, 0, null,null);
//
//            if (comparison.size() > 0) {
//                wosBasic.setJsonFlag(1);
//                wosBasic.setIsShow(comparison.stream().filter(s -> s.getIsShow().equals(1)).findAny().isPresent() ? 1 : 0);
//                wosBasic.setJsonResult(comparison);
//                wosBasic.setNetJsonFlag(-1);
//                wosBasic.setNetListId(listOrgin.stream().map(FileDetails::getId).collect(Collectors.toList()));
//                wosBasicMapper.updateById(wosBasic);
//            }
//        }
//    }

    /**
     * 异步目录对比
     *
     * @param uts
     */
    // @Async
    public void contentsComparisonStep(Integer orginId, Integer targetId, List<FileDetails> orginList, List<FileDetails> targetList, String userId, Integer parts, Integer direction, String contentsComparisonKey) {
        TimeInterval timer = DateUtil.timer();
        List<FileDetails> orginR = orginList;
        List<FileDetails> tartgetR = targetList;
//
//        for (FileDetails fileDetails : orginList) {
//            List<FileDetails> list = this.list(Wrappers.<FileDetails>lambdaQuery().eq(FileDetails::getFId, fileDetails.getId()).eq(FileDetails::getTpye, 8).eq(FileDetails::getPartDirct, parts.toString() + direction.toString()));
//            if (list.size() == 0) {
//                list = cutImageUtil.imgClice(parts, direction, fileDetails, userId);
//                this.saveOrUpdateBatch(list);
//            }
//            orginR.addAll(list);
//        }
//
//        if (NumberUtil.equals(orginId, targetId)) {
//            tartgetR = orginR;
//        } else {
//            for (FileDetails fileDetails : targetList) {
//                List<FileDetails> list = this.list(Wrappers.<FileDetails>lambdaQuery().eq(FileDetails::getFId, fileDetails.getId()).eq(FileDetails::getTpye, 8).eq(FileDetails::getPartDirct, parts.toString() + direction.toString()));
//                if (list.size() == 0) {
//                    list = cutImageUtil.imgClice(parts, direction, fileDetails, userId);
//                    this.saveOrUpdateBatch(list);
//                }
//                tartgetR.addAll(list);
//            }
//        }
        log.info("目录对比切割耗时:{}", timer.intervalRestart());

        redisUtil.saveObject(contentsComparisonKey, "图片切割完成,正在对比中...");

        orginR.stream().parallel().forEach(f -> {
            f.setVector(featureService.imageFeature(f.getPath()));
            f.setIsWhite(imageComparison.checkWhiteBlock(f.getPath()));
        });

        if (NumberUtil.equals(orginId, targetId)) {
            tartgetR = orginR;
        } else {
            tartgetR.stream().parallel().forEach(f -> {
                f.setVector(featureService.imageFeature(f.getPath()));
                f.setIsWhite(imageComparison.checkWhiteBlock(f.getPath()));
            });
        }
        log.info("目录对比获取向量耗时:{}", timer.intervalRestart());

        List<ContentsComparisonRes> r = imageComparison.comparisonSort(orginR, tartgetR, Integer.valueOf(userId), false, contentsComparisonKey);
        log.info("目录对比排序耗时:{}", timer.intervalRestart());
        if (r.size() > 0) {
            redisUtil.saveObject(contentsComparisonKey, JSONObject.toJSONString(r.stream().sorted(Comparator.comparing(ContentsComparisonRes::getMax).reversed()).collect(Collectors.toList())));
        } else {
            redisUtil.saveObject(contentsComparisonKey, 99);
        }
        redisUtil.decrement(userId);
    }

    /**
     * 异步连线图对比
     *
     * @param uts
     */

    public void contentsComparisonLineStep(boolean isSave, Integer orginId, Integer targetId, List<FileDetails> orginList, List<FileDetails> targetList, String userId, Integer level, String contentsComparisonKey) {
        TimeInterval timer = DateUtil.timer();
        List<FileDetails> orginR = orginList;

        List<FileDetails> tartgetR = targetList;

        log.info("连线对比切割耗时:{}", timer.intervalRestart());

        redisUtil.saveObject(contentsComparisonKey, "图片切割完成,正在对比中...");
        SearchRecord searchRecord = new SearchRecord();
        if (isSave) {
            searchRecord.setLevel(level + 1);
            searchRecord.setSource(6);
            searchRecord.setUId(Integer.parseInt(userId));
            searchRecord.setCreateTime(System.currentTimeMillis());
            searchRecord.setRId(orginR.get(0).getRid());

            searchRecord.setTopk(orginR.size());
            searchRecord.setStatus(-1);
            searchRecord.setReadStatus(-1);

            searchRecordService.saveOrUpdate(searchRecord);
        }

        orginR.stream().parallel().forEach(f -> {
            f.setArray(nacosUtil.numIdentify(f.getPath()));
            f.setVector(featureService.imageFeature(f.getPath()));
            f.setIsWhite(imageComparison.checkWhiteBlock(f.getPath()));
        });

        if (NumberUtil.equals(orginId, targetId)) {
            tartgetR = orginR;
        } else {
            tartgetR.stream().forEach(f -> {
                f.setArray(nacosUtil.numIdentify(f.getPath()));
                f.setVector(featureService.imageFeature(f.getPath()));
                f.setIsWhite(imageComparison.checkWhiteBlock(f.getPath()));
            });
        }
        log.info("连线对比获取向量耗时:{}", timer.intervalRestart());

        List<ContentsComparisonRes> r = imageComparison.comparisonSortWithLine(orginR, tartgetR, Integer.valueOf(userId), 1, level, contentsComparisonKey, "inform.fast");


        log.info("连线对比排序耗时:{}", timer.intervalRestart());
        if (r.size() > 0) {
            if (isSave) {
                searchRecord.setFinishTime(System.currentTimeMillis());
                searchRecord.setStatus(1);
                searchRecord.setJsonResult(r.stream().sorted(Comparator.comparing(ContentsComparisonRes::getMax).reversed()).filter(rs -> rs.getIsShow().equals(1)).collect(Collectors.toList()));
                searchRecordService.saveOrUpdate(searchRecord);
            } else {
                redisUtil.saveObject(contentsComparisonKey, JSONObject.toJSONString(r.stream().sorted(Comparator.comparing(ContentsComparisonRes::getMax).reversed()).filter(rs -> rs.getIsShow().equals(1)).collect(Collectors.toList())));
            }
        } else {
            redisUtil.saveObject(contentsComparisonKey, "对比完成,无相似内容");
        }
        redisUtil.decrement(userId);
    }


    public void contentsComparisonLineSiginStep(Integer id, Integer source, String[] rids, String userId, String contentsComparisonKey, Integer level, FileRecord record) {
        TimeInterval timer = DateUtil.timer();
        FileDetails fileDetails = this.getById(id);
//        fileDetails.setId(-1);
        fileDetails.setArray(nacosUtil.numIdentify(fileDetails.getPath()));
        fileDetails.setFPath(this.getById(fileDetails.getFId()).getPath());
        fileDetails.setVector(featureService.imageFeature(fileDetails.getPath()));
        fileDetails.setIsWhite(imageComparison.checkWhiteBlock(fileDetails.getPath()));
        List<Float> floats = featureService.imageFeature(fileDetails.getPath());

        int total = 0;
        List<ReturnImage> returnImages = new ArrayList<>();
        fileDetails.setPmid(Optional.ofNullable(record.getPmut()).orElse("0"));
        FetchVectorVoStep fetchVectorVoStep;
        if (source == 2) {
            fetchVectorVoStep = searchSelfService.pubSearchImage(50, floats.stream().map(Float::doubleValue).collect(Collectors.toList()), Arrays.asList(rids), record.getPmut());
        } else {
            fetchVectorVoStep = searchSelfService.pubSearchImage(singleNum, floats.stream().map(Float::doubleValue).collect(Collectors.toList()), source, record.getPmut());
        }

        log.info("检索耗时：{}", timer.intervalRestart());
        if (fetchVectorVoStep != null) {
            List<ComparisonRes> lineTemp = new ArrayList<>();
            List<ComparisonRes> firstTemp = new ArrayList<>();
            List<PubVectorImageRes> datas = fetchVectorVoStep.getData();
            List<List<PubVectorImageRes>> lists = ImageComparison.groupListByCount(datas, 10);

            redisUtil.saveObject(contentsComparisonKey, NumberUtil.div(10, lists.size() + 10, 2));
            for (int i = 0; i < lists.size(); i++) {
                TimeInterval timer1 = DateUtil.timer();
                List<FileDetails> netList = new ArrayList<>();

                for (PubVectorImageRes hit : lists.get(i)) {
                    Integer table_no = hit.getTable_no();
                    Integer serial_id = hit.getSerial_id();
                    Integer top_x = hit.getTop_x();
                    Integer top_y = hit.getTop_y();
                    Integer bottom_x = hit.getBottom_x();
                    Integer bottom_y = hit.getBottom_y();
                    String pmid_ut = hit.getPm();
                    String img_name = hit.getImg_name();

                    FileDetails one = this.getOne(Wrappers.<FileDetails>lambdaQuery().eq(FileDetails::getTpye, -1).eq(FileDetails::getTableNo, table_no).eq(FileDetails::getSerialId, serial_id).last("limit 1"));

                    String tableMark = "ncbi_pdf_to_jpg_" + table_no;
                    NcbiPdfToJpg imageData;
                    try {
                        imageData = bussService.getImgData(serial_id, tableMark);
                    } catch (Exception e) {
                        continue;
                    }

                    if (null == one) {
                        String fileName = imageData.getFileName();
                        String path = minioUtil.upload(new ByteArrayInputStream(imageData.getFigureZip()), Integer.valueOf(userId), DateUtil.today(), fileName, Scenario.view);
                        FileDetails fileDetailsInner = new FileDetails().setFId(record.getId()).setRid(record.getId()).setTpye(-1).setTableNo(table_no).setSerialId(serial_id).setPath(path).setPmid(AesEncryptUtils.encrypt(imageData.getPmidUt()));
                        this.save(fileDetailsInner);
                        one = fileDetailsInner;
                    }


                    FileDetails filedetalInner = this.getOne(Wrappers.<FileDetails>lambdaQuery()
                            .eq(FileDetails::getTpye, -2)
                            .eq(FileDetails::getTopX, top_x)
                            .eq(FileDetails::getBottomX, bottom_x)
                            .eq(FileDetails::getTopY, top_y)
                            .eq(FileDetails::getBottomY, bottom_y)
                            .eq(FileDetails::getFId, one.getId())
                            .last("limit 1"));


                    if (null == filedetalInner) {
                        Image image = extractUtil.byteArrayToImage(imageData.getFigureZip());
                        if (null == image) {
                            continue;
                        }
                        Mat src = Imgcodecs.imdecode(new MatOfByte(imageData.getFigureZip()), Imgcodecs.IMREAD_COLOR);
                        Mat croppedImage = new Mat(src, new Rect(top_x, top_y, bottom_x - top_x, bottom_y - top_y));
                        String innerFile = minioUtil.upload(minioUtil.coverInput(croppedImage), Integer.valueOf(userId), DateUtil.today(), img_name, Scenario.view);
                        filedetalInner = new FileDetails();
                        filedetalInner.setPath(innerFile);
                        filedetalInner.setTpye(-2);
                        filedetalInner.setFId(one.getId());
                        filedetalInner.setPmid(AesEncryptUtils.encrypt(imageData.getPmidUt()));
                        filedetalInner.setTopX(top_x);
                        filedetalInner.setTopY(top_y);
                        filedetalInner.setBottomX(bottom_x);
                        filedetalInner.setBottomY(bottom_y);
                        this.saveOrUpdate(filedetalInner);
                        netList.add(filedetalInner.setFPath(one.getPath()).setVector(hit.getVector()));
                    } else {
                        netList.add(filedetalInner.setFPath(one.getPath()).setVector(hit.getVector()));
                    }

                }

                List<FileDetails> netFinalList = netList.stream().filter(f -> !StrUtil.isNullOrUndefined(f.getPath())).map(f -> {
                    if (null == f.getVector()) {
                        f.setVector(featureService.imageFeature(f.getPath()));
                    }
                    f.setArray(nacosUtil.numIdentify(f.getPath()));
                    f.setIsWhite(imageComparison.checkWhiteBlock(f.getPath()));
                    return f;
                }).collect(Collectors.toList());

                if (null == fileDetails.getVector()) {
                    fileDetails.setVector(featureService.imageFeature(fileDetails.getPath()));
                }
                long l1 = timer1.intervalRestart();
                TimeInterval timer2 = DateUtil.timer();
                List<ContentsComparisonRes> contentsComparisonRes = imageComparison.comparisonSortWithLine(Arrays.asList(fileDetails.setPmid(minioUtil.getUrl(record.getFilePath()))), netFinalList, Integer.valueOf(userId), 0, level, null, "inform.normal");
                long l2 = timer2.intervalRestart();
                log.info("组装数据耗时：{},数据计算耗时：{}", l1, l2);
                if (null != contentsComparisonKey) {
                    redisUtil.saveObject(contentsComparisonKey, NumberUtil.div(i + 11, lists.size() + 10, 2));
                }

                if (contentsComparisonRes.get(0).getHasPiclist().size() > 0) {
                    lineTemp.addAll(contentsComparisonRes.get(0).getHasPiclist());
                }
                if (i == 0) {
                    firstTemp = contentsComparisonRes.get(0).getList();
                }
                if (lineTemp.size() >= 10) {
                    break;
                }


            }
            if (lineTemp.size() > 0) {
                firstTemp.addAll(lineTemp);
            }
            firstTemp = firstTemp.stream().distinct().limit(10).collect(Collectors.toList());
            ContentsComparisonRes contentsComparisonResReal = new ContentsComparisonRes();
            contentsComparisonResReal.setMax(firstTemp.stream().mapToDouble(ComparisonRes::getV).max().getAsDouble());
            contentsComparisonResReal.setIsShow(firstTemp.stream().filter(ComparisonRes::isHasPic).findAny().isPresent() ? 1 : 0);
            contentsComparisonResReal.setFileDetails(fileDetails);
            contentsComparisonResReal.setList(firstTemp);
            redisUtil.saveObject(contentsComparisonKey, JSONObject.toJSONString(Arrays.asList(contentsComparisonResReal)));
            redisUtil.decrement(userId);
        }
    }


    /**
     * 异步连线图对比
     *
     * @param uts
     */
    //@Async
    public void machineComparisonStep(List<FileDetails> orginList, Integer userId, Integer rid, Integer type, String contentsComparisonKey) {
        System.out.println("自动化对比_步骤二");
        int present = 1;
        List<FileDetails> collect = orginList.stream().filter(o -> o.getSplitStatus() == 0).collect(Collectors.toList());

        collect.parallelStream().forEach(f -> {
            List<FileDetails> work = cutImageUtil.workfiligreeNoId(f.getPath(), f.getId(), f.getRid(), -1, userId);
            if (work == null || work.size() == 0) {
                return;
            }
            this.saveOrUpdateBatch(work);
            this.updateById(new FileDetails().setId(f.getId()).setSplitStatus(1));
            if (null != contentsComparisonKey) {
                redisUtil.saveObject(contentsComparisonKey, NumberUtil.div(collect.size() - 1, collect.size(), 2));
            }
        });


        List<Integer> dict = orginList.stream().map(FileDetails::getId).collect(Collectors.toList());

        type = type == 0 ? 4 : 7;

        List<FileDetails> data1 = this.list(Wrappers.<FileDetails>lambdaQuery().eq(FileDetails::getRid, rid).eq(FileDetails::getTpye, type).in(FileDetails::getFId, dict).eq(FileDetails::getDeleteFlag, 0));
        List<FileDetails> data2 = this.list(Wrappers.<FileDetails>lambdaQuery().eq(FileDetails::getRid, rid).eq(FileDetails::getTpye, type).in(FileDetails::getFId, dict).eq(FileDetails::getDeleteFlag, -1));
        List<List<FileDetails>> lists = Arrays.asList(data1, data2);

        if (data1.size() > 0 || data2.size() > 0) {
            redisUtil.saveObject(contentsComparisonKey, JSONObject.toJSONString(lists));
        } else {
            redisUtil.saveObject(contentsComparisonKey, "对比完成,无相似内容");
        }
        redisUtil.decrement(userId.toString());
    }
}
